package V20.src.main.java.com.birdboot.controller;

import com.birdboot.annotation.Controller;
import com.birdboot.annotation.RequestMapping;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;
import com.birdboot.util.DBUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用于处理与用户数据相关的业务
 */
@Controller
public class UserController {
    //表示保存所有用户信息的目录users
    private static File userDir;

    static{
        userDir = new File("./users");
        if(!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    /**
     * 注册功能
     * @param request
     * @param response
     */
    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册!!!");

        request.getHeader("Content-Length");

        //1获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        //必要的验证
        if(username==null||username.isEmpty()||
           password==null||password.isEmpty()||
           nickname==null||nickname.isEmpty()||
           ageStr==null||ageStr.isEmpty()||
           !ageStr.matches("[0-9]+")
        ){
            response.sendRedirect("/reg_info_error.html");
            return;
        }

        int age = Integer.parseInt(ageStr);
        /*
            注册逻辑 - 数据库
         */
        try (Connection connection = DBUtil.getConnection();){
            /*
                校验用户名是否被占用
             */
            String checkSql = "SELECT id FROM userinfo WHERE username=?";
            PreparedStatement ps1 = connection.prepareStatement(checkSql);
            ps1.setString(1, username);
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()){ //用户名被占用
                response.sendRedirect("/have_user.html");
            }else{ //未被占用
                /*
                    执行注册用户流程
                 */
                String insSql = "INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
                PreparedStatement ps2 = connection.prepareStatement(insSql);
                ps2.setString(1, username);
                ps2.setString(2, password);
                ps2.setString(3, nickname);
                ps2.setInt(4, age);
                int i = ps2.executeUpdate();
                if (i>0){
                    response.sendRedirect("/reg_success.html");
                }else{
                    response.sendRedirect("/reg_info_error.html");
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

    /**
     * 登录功能
     * @param request
     * @param response
     */
    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理用户登录!!!!");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+","+password);
        //添加必要的验证,用户名或密码没输入则跳转login_info_error.html
        if(username==null||username.isEmpty()||
                password==null||password.isEmpty()){
            response.sendRedirect("/login_info_error.html");

            return;
        }
        /*
            登录功能判断 - 数据库版本
            1.userinfo表中查询数据(用户名和密码)
            2.查询结果判断
              2.1 正确：登录成功, 到 login_success.html
              2.2 失败：用户名或密码错误, 到 login_fail.html
         */
        try (Connection connection = DBUtil.getConnection();){
            String sql = "SELECT username,password,nickname " +
                    "FROM userinfo " +
                    "WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet resultSet = ps.executeQuery();
            // 结果判断
            if (resultSet.next()){
                response.sendRedirect("/login_success.html");
            }else{
                response.sendRedirect("/login_fail.html");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


    }

    /**
     * 修改密码
     * @param request
     * @param response
     */
    /**
     * 修改密码
     * @param request
     * @param response
     */
    @RequestMapping("/updatePWD")
    public void updatePWD(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始修改密码");
        /*
            1.接收数据(用户名、原密码、新密码)
            2.连接数据库,完成修改密码功能
            3.校验原密码是否正确
              正确: 执行修改密码功能：pwd_success.html  <h1>修改密码成功</h1>
              错误: 修改密码失败：pwd_fail.html     <h1>原密码错误</h1>
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String newPassword = request.getParameter("newPassword");

        // 连接数据库
        try (Connection connection = DBUtil.getConnection();){
            // 校验原密码
            String pwdSql = "SELECT id FROM userinfo " +
                    "WHERE username=? AND password=?";
            PreparedStatement ps1 = connection.prepareStatement(pwdSql);
            ps1.setString(1, username);
            ps1.setString(2, password);
            ResultSet resultSet = ps1.executeQuery();
            if (resultSet.next()){
                // 原密码正确,开始修改密码
                String updSql = "UPDATE userinfo SET password=? " +
                        "WHERE username=?";
                PreparedStatement ps2 = connection.prepareStatement(updSql);
                ps2.setString(1, newPassword);
                ps2.setString(2, username);
                int i = ps2.executeUpdate();
                if (i>0){
                    // 修改密码成功页面
                    response.sendRedirect("/pwd_success.html");
                }else{
                    // 修改密码失败页面
                    response.sendRedirect("/pwd_fail.html");
                }
            }else{
                // 修改密码失败页面
                response.sendRedirect("/pwd_fail.html");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
